package com.sangmo.boot.auth.core.handlers.impl;

import com.sangmo.boot.auth.core.AuthorizeCodeService;
import com.sangmo.boot.auth.core.interfaces.GrantCodeRequest;
import com.sangmo.boot.auth.core.model.AuthorizeCode;
import com.sangmo.boot.auth.core.model.Client;
import com.sangmo.boot.auth.core.handlers.BaseAuthorizeCodeHandler;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;

public class DefaultAuthorizeCodeHandler extends BaseAuthorizeCodeHandler {

    @Autowired
    protected AuthorizeCodeService authorizeCodeService;

    @Value("${authorize.code.create.always}")
    private boolean alwaysCreateNew = true;
    @Value("${authorize.code.length}")
    private int length = 6;
    @Value("${authorize.code.validity}")
    private int validity = 5 * 60;

    @Override
    protected AuthorizeCode createCode(Client client, GrantCodeRequest req) {
        AuthorizeCode code = authorizeCodeService.findByClientIdAndUsername(req.getClientId(), req.getUsername());
        if (null == code) {
            code = new AuthorizeCode();
            code.setClientId(client.getId());
            code.setUsername(req.getUsername().trim());
        }
        if (null == code.getId() || alwaysCreateNew || code.isExpired()) {
            code.setValidity(validity);
            code.setCode(RandomStringUtils.randomNumeric(length));
            code.setRefreshTime(new Date());
            code.setFailure(0);
            code.setUsedTime(null);
        }
        code.setRandomStr(req.getRandomStr());

        authorizeCodeService.save(code);
        return code;
    }

}
